"""
汽车和加油记录相关的 API 路由
"""

from datetime import datetime
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from src.auth import get_current_active_family_member, require_member
from src.crud.vehicle_crud import (
    # Fuel Record CRUD
    create_fuel_record,
    # Vehicle CRUD
    create_vehicle,
    delete_fuel_record,
    delete_vehicle,
    get_active_vehicles,
    get_fuel_consumption_stats,
    get_fuel_consumption_stats_by_vehicle,
    get_fuel_cost_summary,
    get_fuel_record_by_id,
    get_fuel_records,
    get_fuel_records_by_station_type,
    get_fuel_records_by_vehicle,
    get_latest_fuel_record,
    get_vehicle_by_id,
    get_vehicle_by_license_plate,
    get_vehicles,
    update_fuel_record,
    update_vehicle,
)
from src.database import get_db
from src.models.family_model import FamilyMember
from src.models.vehicle_model import GasStationType
from src.schemas.vehicle_schema import (
    FuelConsumptionStats,
    VehicleCreate,
    VehicleFuelRecordCreate,
    VehicleFuelRecordList,
    VehicleFuelRecordResponse,
    VehicleFuelRecordUpdate,
    VehicleFuelRecordWithStats,
    VehicleList,
    VehicleResponse,
    VehicleUpdate,
    VehicleWithFuelStats,
)

router = APIRouter(tags=["vehicle"])


# ===== Vehicle Management Routes =====


@router.post(
    "/vehicles", response_model=VehicleResponse, status_code=status.HTTP_201_CREATED
)
async def create_vehicle_endpoint(
    vehicle_data: VehicleCreate,
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """创建车辆"""
    # 检查车牌号是否已存在
    existing_vehicle = await get_vehicle_by_license_plate(
        db, vehicle_data.license_plate, current_user.family_id
    )
    if existing_vehicle:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="该车牌号已存在"
        )

    # 创建车辆
    vehicle = await create_vehicle(
        db=db,
        family_id=current_user.family_id,
        name=vehicle_data.name,
        brand=vehicle_data.brand,
        model=vehicle_data.model,
        license_plate=vehicle_data.license_plate,
        year=vehicle_data.year,
        is_active=vehicle_data.is_active,
        notes=vehicle_data.notes,
    )

    return VehicleResponse.model_validate(vehicle)


@router.get("/vehicles/{vehicle_id}", response_model=VehicleResponse)
async def get_vehicle_endpoint(
    vehicle_id: int,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """获取单个车辆"""
    vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
    if not vehicle:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在")
    return VehicleResponse.model_validate(vehicle)


@router.get("/vehicles", response_model=VehicleList)
async def get_vehicles_endpoint(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    is_active: bool | None = Query(None, description="是否活跃"),
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """获取车辆列表"""
    vehicles, total = await get_vehicles(
        db=db,
        family_id=current_user.family_id,
        skip=skip,
        limit=limit,
        is_active=is_active,
    )

    return VehicleList(
        vehicles=[VehicleResponse.model_validate(vehicle) for vehicle in vehicles],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.put("/vehicles/{vehicle_id}", response_model=VehicleResponse)
async def update_vehicle_endpoint(
    vehicle_id: int,
    vehicle_data: VehicleUpdate,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """更新车辆"""
    # 检查车辆是否存在
    existing_vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
    if not existing_vehicle:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在")

    # 如果要更新车牌号,检查是否与其他车辆冲突
    if (
        vehicle_data.license_plate
        and vehicle_data.license_plate != existing_vehicle.license_plate
    ):
        vehicle_with_same_plate = await get_vehicle_by_license_plate(
            db, vehicle_data.license_plate, current_user.family_id
        )
        if vehicle_with_same_plate:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="该车牌号已被其他车辆使用",
            )

    # 准备更新数据
    update_data = {}
    for field, value in vehicle_data.model_dump(exclude_unset=True).items():
        if value is not None:
            update_data[field] = value

    # 更新车辆
    updated_vehicle = await update_vehicle(
        db=db, vehicle_id=vehicle_id, family_id=current_user.family_id, **update_data
    )

    if not updated_vehicle:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="更新失败")

    return VehicleResponse.model_validate(updated_vehicle)


@router.delete("/vehicles/{vehicle_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_vehicle_endpoint(
    vehicle_id: int,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """删除车辆"""
    success = await delete_vehicle(db, vehicle_id, current_user.family_id)
    if not success:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在")


@router.get("/vehicles/with-stats", response_model=list[VehicleWithFuelStats])
async def get_vehicles_with_stats_endpoint(
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """获取带油耗统计的车辆列表"""
    vehicles = await get_active_vehicles(db, current_user.family_id)

    result = []
    for vehicle in vehicles:
        # 获取最新加油记录
        latest_record = await get_latest_fuel_record(
            db, current_user.family_id, vehicle.id
        )

        # 获取油耗统计
        fuel_stats = await get_fuel_consumption_stats_by_vehicle(
            db, vehicle.id, current_user.family_id
        )

        vehicle_with_stats = VehicleWithFuelStats(
            vehicle=VehicleResponse.model_validate(vehicle),
            latest_fuel_record=VehicleFuelRecordResponse.model_validate(latest_record)
            if latest_record
            else None,
            fuel_stats=fuel_stats,
        )
        result.append(vehicle_with_stats)

    return result


# ===== Fuel Record Management Routes =====


@router.post(
    "/fuel-records",
    response_model=VehicleFuelRecordWithStats,
    status_code=status.HTTP_201_CREATED,
)
async def create_fuel_record_endpoint(
    record_data: VehicleFuelRecordCreate,
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """创建加油记录"""
    # 创建记录
    try:
        record = await create_fuel_record(
            db=db,
            family_id=current_user.family_id,
            vehicle_id=record_data.vehicle_id,
            current_mileage=record_data.current_mileage,
            fuel_amount=record_data.fuel_amount,
            fuel_cost=record_data.fuel_cost,
            fuel_price=record_data.fuel_price,
            gas_station_type=record_data.gas_station_type,
            refuel_date=record_data.refuel_date,
            notes=record_data.notes,
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    # 获取统计信息
    stats = await get_fuel_consumption_stats_by_vehicle(
        db, record_data.vehicle_id, current_user.family_id
    )

    return VehicleFuelRecordWithStats(
        record=VehicleFuelRecordResponse.model_validate(record), stats=stats
    )


@router.get("/fuel-records/{record_id}", response_model=VehicleFuelRecordResponse)
async def get_fuel_record_endpoint(
    record_id: int,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """获取单个加油记录"""
    record = await get_fuel_record_by_id(db, record_id, current_user.family_id)
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="加油记录不存在"
        )
    return VehicleFuelRecordResponse.model_validate(record)


@router.get("/fuel-records", response_model=VehicleFuelRecordList)
async def get_fuel_records_endpoint(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    start_date: datetime | None = Query(None, description="开始日期"),
    end_date: datetime | None = Query(None, description="结束日期"),
    gas_station_type: str | None = Query(None, description="加油站类型"),
    vehicle_id: int | None = Query(None, description="车辆ID"),
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """获取加油记录列表"""
    records, total = await get_fuel_records(
        db=db,
        family_id=current_user.family_id,
        skip=skip,
        limit=limit,
        start_date=start_date,
        end_date=end_date,
        gas_station_type=gas_station_type,
        vehicle_id=vehicle_id,
    )

    return VehicleFuelRecordList(
        fuel_records=[
            VehicleFuelRecordResponse.model_validate(record) for record in records
        ],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/vehicles/{vehicle_id}/fuel-records", response_model=VehicleFuelRecordList)
async def get_fuel_records_by_vehicle_endpoint(
    vehicle_id: int,
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """根据车辆ID获取加油记录"""
    # 验证车辆是否存在且属于当前家庭
    vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
    if not vehicle:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在")

    records, total = await get_fuel_records_by_vehicle(
        db=db,
        vehicle_id=vehicle_id,
        family_id=current_user.family_id,
        skip=skip,
        limit=limit,
    )

    return VehicleFuelRecordList(
        fuel_records=[
            VehicleFuelRecordResponse.model_validate(record) for record in records
        ],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.put("/fuel-records/{record_id}", response_model=VehicleFuelRecordWithStats)
async def update_fuel_record_endpoint(
    record_id: int,
    record_data: VehicleFuelRecordUpdate,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """更新加油记录"""
    # 检查记录是否存在
    existing_record = await get_fuel_record_by_id(db, record_id, current_user.family_id)
    if not existing_record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="加油记录不存在"
        )

    # 准备更新数据
    update_data = {}
    for field, value in record_data.model_dump(exclude_unset=True).items():
        if value is not None:
            update_data[field] = value

    # 更新记录
    updated_record = await update_fuel_record(
        db=db, record_id=record_id, family_id=current_user.family_id, **update_data
    )

    if not updated_record:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="更新失败")

    # 获取统计信息
    stats = await get_fuel_consumption_stats_by_vehicle(
        db, updated_record.vehicle_id, current_user.family_id
    )

    return VehicleFuelRecordWithStats(
        record=VehicleFuelRecordResponse.model_validate(updated_record), stats=stats
    )


@router.delete("/fuel-records/{record_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_fuel_record_endpoint(
    record_id: int,
    current_user: FamilyMember = Depends(get_current_active_family_member),
    db: AsyncSession = Depends(get_db),
):
    """删除加油记录"""
    success = await delete_fuel_record(db, record_id, current_user.family_id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="加油记录不存在"
        )


@router.get(
    "/vehicles/{vehicle_id}/fuel-records/latest",
    response_model=VehicleFuelRecordResponse,
)
async def get_latest_fuel_record_endpoint(
    vehicle_id: int,
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """获取指定车辆的最新加油记录"""
    # 验证车辆是否存在且属于当前家庭
    vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
    if not vehicle:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在")

    record = await get_latest_fuel_record(db, current_user.family_id, vehicle_id)
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="暂无加油记录"
        )
    return VehicleFuelRecordResponse.model_validate(record)


@router.get("/fuel-stats/consumption", response_model=Optional[FuelConsumptionStats])
async def get_fuel_consumption_stats_endpoint(
    start_date: datetime | None = Query(None, description="开始日期"),
    end_date: datetime | None = Query(None, description="结束日期"),
    vehicle_id: int | None = Query(None, description="车辆ID"),
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """获取油耗统计信息"""
    if vehicle_id:
        # 验证车辆是否存在且属于当前家庭
        vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
        if not vehicle:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在"
            )
        stats = await get_fuel_consumption_stats_by_vehicle(
            db=db,
            vehicle_id=vehicle_id,
            family_id=current_user.family_id,
            start_date=start_date,
            end_date=end_date,
        )
    else:
        stats = await get_fuel_consumption_stats(
            db=db,
            family_id=current_user.family_id,
            start_date=start_date,
            end_date=end_date,
        )

    return stats


@router.get("/fuel-stats/cost-summary")
async def get_fuel_cost_summary_endpoint(
    start_date: datetime | None = Query(None, description="开始日期"),
    end_date: datetime | None = Query(None, description="结束日期"),
    vehicle_id: int | None = Query(None, description="车辆ID"),
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """获取加油费用汇总"""
    if vehicle_id:
        # 验证车辆是否存在且属于当前家庭
        vehicle = await get_vehicle_by_id(db, vehicle_id, current_user.family_id)
        if not vehicle:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="车辆不存在"
            )

    summary = await get_fuel_cost_summary(
        db=db,
        family_id=current_user.family_id,
        start_date=start_date,
        end_date=end_date,
        vehicle_id=vehicle_id,
    )
    return summary


@router.get(
    "/fuel-records/by-station/{station_type}", response_model=VehicleFuelRecordList
)
async def get_fuel_records_by_station_endpoint(
    station_type: str,
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="每页记录数"),
    current_user: FamilyMember = Depends(require_member),
    db: AsyncSession = Depends(get_db),
):
    """根据加油站类型获取加油记录"""
    records, total = await get_fuel_records_by_station_type(
        db=db,
        family_id=current_user.family_id,
        gas_station_type=station_type,
        skip=skip,
        limit=limit,
    )

    return VehicleFuelRecordList(
        fuel_records=[
            VehicleFuelRecordResponse.model_validate(record) for record in records
        ],
        total=total,
        skip=skip,
        limit=limit,
    )


@router.get("/fuel-stations/types", response_model=list[str])
async def get_gas_station_types():
    """获取支持的加油站类型列表"""
    return GasStationType.get_all_types()
